package Reflect;

import java.lang.reflect.Field;

public class Reflect2 {
    public static void main(String[] args) throws Exception {
        Class personClass = Person.class;
        //获取成员变量们
        Field[] fields = personClass.getFields();
        //获取所有public修饰出成员变量
        for (Field field : fields) {
            System.out.println(field);
        }

        System.out.println("==================");
        Field a = personClass.getField("a");
        //获取成员变量a的值
        Person p = new Person();
        Object value = a.get(p);
        System.out.println(value);
        //传回null
        a.set(p,"张三");
        System.out.println(p);

        Field[] declaredFields = personClass.getDeclaredFields();
        //获取所有的成员变量,不考虑修饰符
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }
        /*private java.lang.String Reflect.Person.name
        private int Reflect.Person.age
        public java.lang.String Reflect.Person.a*/
        Field name = personClass.getDeclaredField("name");
        //要注意这里的方法后面有没有加一个s
        name.setAccessible(true);
        //上面这个叫暴力反射
        //下面的直接打印会报错,因为name是private类的
        //要先让他忽略访问修饰符
        Object value2 = name.get(p);
        System.out.println(value2);
    }
}
